package leetcode.tree;

import java.util.ArrayDeque;

public class Lc1161 {


    public int maxLevelSum(TreeNode root) {
        int level = 0;
        int maxSum = Integer.MIN_VALUE;
        if (root == null) return 0;
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        queue.offerLast(root);
        int step = 0;
        while (!queue.isEmpty()) {
            int sum = 0;
            step++;
            for (int size = queue.size(); size > 0; size--) {
                TreeNode node = queue.pollFirst();
                sum += node.val;
                if (node.left != null) queue.offerLast(node.left);
                if (node.right != null) queue.offerLast(node.right);
            }
            if (sum > maxSum) {
                maxSum = sum;
                level = step;
            }
        }
        return level;
    }


}
